package com.jwaoo.chat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import com.dx.as.JWCache;
import com.dx.as.common.log.LogUtil;
import com.dx.as.utils.Utils;
import com.dx.as.utils.WakeAndLock;
import com.google.gson.Gson;
import com.jwaoo.chat.activity.P2PMessageActivity;
import com.jwaoo.chat.activity.module.fromapp.AppInstance;
import com.jwaoo.chat.attachment.FileAttachment;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.receiver.NotificationBroadcastReceiver;
import com.jwaoo.chat.session.Extras;
import com.jwaoo.chat.session.audio.AudioState;
import com.jwaoo.chat.session.avchat.AVChatState;
import com.jwaoo.chat.session.avchat.AVChatType;
import com.jwaoo.chat.session.avchat.FloatView;
import com.jwaoo.im.ImClient;
import com.jwaoo.protobuf.ImBase;
import com.jwaoo.protobuf.ImCommand;
import com.jwaoo.protobuf.ImEvent;
import com.jwaoo.protobuf.ImResponse;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import static com.jwaoo.chat.data.db.MessageHandler.SAVE_MESSAGE;
import static com.jwaoo.chat.data.db.MessageHandler.UPDATE_MESSAGE;

/**
 * Created by jwaoo on 2017/7/4.
 */

public class IMessageClient extends ImClient{
    private Gson gson = new Gson();
    private String  token;
    private Map<Integer,Message> messageMap = new HashMap<>();
//    private String client_id = "5972c401a210fecf8929b714";
    private String client_id = "598837f87435cf7fc9105126";
    public IMessageClient() {
        super();
    }

    public void setToken(String token){
        this.token = token;
    }

    @Override
    public boolean onConnected(Socket socket) {
        try{
            this.doLogin(token, ImBase.ImClientType.IM_CLIENT_ANDROID,client_id);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return true;
    }

    public boolean sendMessage(Message message,String json){
        messageMap.put(message.getMsgid(),message);
        boolean needFast = false;
        if (message.getMsgtype() == AVChatType.AUDIO.getValue() || message.getMsgtype() == AVChatType.VIDEO.getValue()) needFast = true;
        boolean isSuccess = sendMessage(message.getMsgid(), message.getFriend(),11,json,needFast);
        LogUtil.d("sendMessage","json : "+json);
        return isSuccess;
    }

    @Override
    public void onDisconnected() {
        LogUtil.e("IMessageClient","onDisconnected");
        super.onDisconnected();
    }

    @Override
    public void onLoginSuccess() {
        super.onLoginSuccess();
        LogUtil.e("IMessageClient","loginSuccess");
        MessageHandler.getInstace(ChatHelpter.getContext()).updateUnReadMessage();
    }

    @Override
    public void onLoginFailed() {
        super.onLoginFailed();
        LogUtil.e("IMessageClient","loginFailed");
//        AppInstance.getInstance().onKickedOffline();
    }

    @Override
    public void onSendMessageSuccess(ImCommand.ImMessageInfo message, ImResponse.ImMessageResponse response) {
        onSendMessageCallback(message.getMsgId(),ChatConstants.success ,response.getSendTime());
        LogUtil.d("IMessageClient","onSendMessageSuccess");
    }

    //消息发送成功回执
    public void onSendMessageCallback(int msgId ,int state,long time){
        Message message = messageMap.get(msgId);
        message.setTimestamp(time*1000L);
        message.setState(state);
        MessageHandler.getInstace(JWCache.getContext()).handlerMessages(UPDATE_MESSAGE,message);
        //音视频消息不需要回执
        if (AVChatType.isAVChat(message.getMsgtype())) return;
        MessageHandler.getInstace(ChatHelpter.getContext()).sendMessageBroad(message);
    }

    @Override
    public void onSendMessageFailed(ImCommand.ImMessageInfo message, ImResponse.ImMessageResponse response) {
        onSendMessageCallback(message.getMsgId(),ChatConstants.fail,message.getSendTime());
        LogUtil.d("IMessageClient","onSendMessageFailed");
    }

    @Override
    public boolean onOfflineMessageReceived(ImCommand.ImMessageInfo info) {
        //收到google推送通知的时候，会唤醒IM，再者，音视频通话添加了时间过滤，所以不用特别处理离线消息。
        return onMessageReceived(info.getMsgData(),info.getSendTime(),info.getUserId());
    }

    @Override
    public boolean onOnlineMessageReceived(ImCommand.ImMessageInfo info) {
        LogUtil.d("jsonStr","info = "+info);
        return onMessageReceived(info.getMsgData(),info.getSendTime(),info.getUserId());
    }

    public boolean onMessageReceived(String msgData,long time,int friend){
        try{
            //获取消息体
            String jsonStr = new String(msgData);
            LogUtil.d("jsonStr","strs: "+jsonStr +"   time: "+time);
            //生成消息对象
            Message message = gson.fromJson(jsonStr,Message.class);
            message.setFriend(friend);
            //消息时间
            message.setTimestamp(time*1000L);
            message.setState(ChatConstants.success);
            makeMessage(message);
        }catch (Exception ex){
            LogUtil.e("IMessageClient",ex.toString());
        }
        return true;
    }

    private void makeMessage(Message message){
        //基本类型
        //消息补全附件信息
        if (message.getAttachment() == null) message.setAttachment(new FileAttachment());

        //复杂类型，音视频；
        if (AVChatType.isAVChat(message.getMsgtype())){
            //check 数据，如果数据已经存在，只更新状态
            if (messageMap.containsKey(message.getMsgid())){
                int attachState = message.getAttachment().getAttachstate();
                message = messageMap.get(message.getMsgid());
                message.getAttachment().setAttachstate(attachState);
            }
            //目前正在进行音视频会话
            if (FloatView.getInstance().isStart()){
                //不要做其他的处理，直接发送广播给AVChat页面直接处理消息
                sendAVChatBroad(message);
                return;
            }else {
                //发起音视频会话请求,过滤掉超时请求
                if (message.getAttachment().getAttachstate() == AVChatState.request.getValue() && System.currentTimeMillis()-message.getTimestamp() < 30*1000L){
                    message.setDirect(ChatConstants.In);
                    final Message msg = message;
                    AppInstance.getInstance().getMainContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            FloatView.getInstance().launch(msg);
                        }
                    });

                }else{
                    MessageHandler.getInstace(ChatHelpter.getContext()).handlerMessages(UPDATE_MESSAGE,message);
                    //如果没有，说明是离线消息并且最开始接受的状态不是 AVChatState.request
                    return;
                }
            }
        }else {
            if (messageMap.containsKey(message.getMsgid())){
                return;
            }
        }
        //语音消息设置为unread状态
        if (message.getMsgtype() == ChatConstants.audio){
            message.setIsRead(AudioState.unread.getValue());
        }
        message.setDirect(ChatConstants.In);

        //消息存数据库
        MessageHandler.getInstace(ChatHelpter.getContext()).handlerMessages(SAVE_MESSAGE,message);
        //消息缓存
        messageMap.put(message.getMsgid(),message);
        //如果消息是当前聊天对象发过来的,不发消息提醒
        if (ChatHelpter.currentSessionId != message.getFriend()){
            Utils.startAlarm(ChatHelpter.getContext());
            Utils.doVibrate(ChatHelpter.getContext());
            if (AppInstance.getInstance().isBackground() && !AVChatType.isAVChat(message.getMsgtype())){
                showN();
            }

        }
        if (ChatHelpter.currentSessionId == message.getFriend())
            MessageHandler.getInstace(ChatHelpter.getContext()).sendMessageBroad(message);
    }

    private void sendAVChatBroad(Message message){
        Intent intentMessage = new Intent();
        intentMessage.setAction(ChatConstants.ACTION_AV_MESSAGE);
        intentMessage.putExtra(Extras.EXTRA_MESSAGE,message);
        ChatHelpter.getContext().sendBroadcast(intentMessage);
    }

    @Override
    public void onKickedOffline(ImEvent.ImEventKickOffline event) {
        super.onKickedOffline(event);
        AppInstance.getInstance().onKickedOffline();
        this.stop();
        LogUtil.d("IMessageClient","onKickedOffline:"+event.toString());
    }

    public void prErrInfo(String message) {
        LogUtil.e("IMessageClient","ErrInfo:"+message);
    }

    public void prWarnInfo(String message) {
        LogUtil.w("IMessageClient","WarnInfo:"+message);
    }

    public void prDbgInfo(String message) {
        LogUtil.d("IMessageClient","DbgInfo"+message);
    }
    private void sendNotification(int account) {
        Class<?> cls = AppInstance.getInstance().getCurrentActivity();
        Intent intent = null;
//        if (cls != null){
//            intent = new Intent(ChatHelpter.getContext(), cls);
//            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        }else {
//            intent = new Intent(ChatHelpter.getContext(), P2PMessageActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//        }
        intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                Bundle bundle = new Bundle();
        bundle.putInt(Extras.EXTRA_ACCOUNT, account);
        intent.putExtras(bundle);

        PendingIntent pendingIntent = PendingIntent.getActivity(ChatHelpter.getContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        PowerManager pm = (PowerManager) ChatHelpter.getContext().getSystemService(Context.POWER_SERVICE);
        boolean screen = pm.isScreenOn();
        if (!screen){
            WakeAndLock lock = new WakeAndLock();
            lock.screenOn();
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ChatHelpter.getContext())
                .setContentTitle("消息提示")
                .setContentText("您有一条新信息！")
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setContentInfo("Hello")
                .setTicker("您有一条新信息！")
//                .setVisibility(Notification.VISIBILITY_PUBLIC)
//                .setPriority(Notification.PRIORITY_DEFAULT)
//                .setFullScreenIntent(pendingIntent,false)
                .setSmallIcon(R.drawable.nim_actionbar_nest_dark_logo);
        if (Build.VERSION.SDK_INT >= 21) {
            notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
            notificationBuilder.setCategory(Notification.CATEGORY_MESSAGE);
        }
        Notification notification = notificationBuilder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        NotificationManager notificationManager = (NotificationManager) ChatHelpter.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int)System.currentTimeMillis(), notification);
    }

    private void showN(){
        int type = (int)System.currentTimeMillis();
        Intent intentClick = new Intent(ChatHelpter.getContext(),  NotificationBroadcastReceiver.class);
        intentClick.setAction("notification_clicked");
        intentClick.putExtra(NotificationBroadcastReceiver.TYPE, type);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(ChatHelpter.getContext(), 0, intentClick, PendingIntent.FLAG_ONE_SHOT);

        Intent intentCancel = new Intent(ChatHelpter.getContext(), NotificationBroadcastReceiver.class);
        intentCancel.setAction("notification_cancelled");
        intentCancel.putExtra(NotificationBroadcastReceiver.TYPE, type);
        PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(ChatHelpter.getContext(), 0, intentCancel, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        PowerManager pm = (PowerManager) ChatHelpter.getContext().getSystemService(Context.POWER_SERVICE);
        boolean screen = pm.isScreenOn();
        if (!screen){
            WakeAndLock lock = new WakeAndLock();
            lock.screenOn();
        }
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ChatHelpter.getContext())
                .setContentTitle("消息提示")
                .setContentText("您有一条新信息！")
                .setAutoCancel(true)
                .setContentInfo("Hello")
                .setTicker("您有一条新信息！")
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setPriority(Notification.PRIORITY_DEFAULT)
//                .setFullScreenIntent(pendingIntent,false)
                .setSmallIcon(R.drawable.nim_actionbar_nest_dark_logo)
                .setContentIntent(pendingIntentClick)
                .setDeleteIntent(pendingIntentCancel);

        NotificationManager notificationManager = (NotificationManager) ChatHelpter.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int)System.currentTimeMillis(), notificationBuilder.build());
    }
}
